package com.cnjson.sensor.db.service;

import com.cnjson.sensor.db.entity.EquipmentState;
import com.cnjson.sensor.db.utils.DaoUtils;
import com.cnjson.sensor.db.utils.JdbcUtils;
import com.cnjson.sensor.db.utils.SetIdUtils;
//import com.cnjson.sensor.nio.SocketServer;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

/**
 * 
 * @author lili
 *
 */
public class EquipmentStateService {
//	private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
    private static EquipmentStateService instance;

    public static EquipmentStateService getInstance()
    {
        if (instance == null) {
            instance = new EquipmentStateService();
        }
        return instance;
    }

    /**
     * 根据当前日志消息是否被“消费”，来确定是否接收到修改控制设备控制请求
     *
     * @param del
     *          消费标记
     * @return Map<String, String>
     *          消费结果，将日志id,备注，操作类型返回
     */
    public Map<String, String> getMessageQueue(String del)
    {
        String sql = "SELECT id, remarks, operate_type FROM ift_ctrl_equipment_log WHERE return_result = '-1' AND del_flag = ? ORDER BY request_time ASC LIMIT 1";
        Map<String, Object> result = DaoUtils.queryMap(sql, new Object[] { del });
        if (result == null) {
            return null;
        }
        Map<String, String> map = new HashMap();
        map.put("id", (String)result.get("id"));
        map.put("remarks", (String)result.get("remarks"));
        map.put("operateType", (String)result.get("operate_type"));
        return map;
    }

	/**
	 * 添加设备状态
	 * 
	 * @param e
	 */
	public void addEquipmentState(EquipmentState e) {
		if (e != null) {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			String sql = "INSERT INTO ift_equipment_status(id, equipment_id, running_state, "
					+ "communication_time, cur_time, signal_intensity, heartbean_type, link_type, reporting_cycle,"
					+ "acquisition_cycle, storage_cycle, stored_data, unreported_data, equipment_energy,remote_address,"
					+ "create_by, create_date, update_date,remarks, del_flag) values('" + e.getId() + "','"
					+ e.getEquipmentId() + "','" + e.getRunningState() + "','" + sdf.format(e.getCommunicationTime())
					+ "','" + sdf.format(e.getCurTime()) + "','" + e.getSignalIntensity() + "','" + e.getHeartbeatType()
					+ "','" + e.getLinkType() + "','" + e.getReportingCycle() + "','" + e.getAcquisionCycle() + "','"
					+ e.getStorageCycle() + "'," + e.getStoredData() + "," + e.getUnreportedData() + ","
					+ e.getEquipmentEnergy() + ",'" + e.getRemoteAddress() + "','" + e.getCreateBy() + "','"
					+ sdf.format(e.getCreateDate()) + "','" + sdf.format(e.getUpdateDate()) + "','" + e.getRemarks()
					+ "','" + e.getDelFlag() + "')";
			// int state = DaoUtils.update(sql);
			DaoUtils.update(sql);
		} else
			;
	}

	/**
	 * 更新设备状态
	 * 
	 * @param e
	 *            [description]
	 */
	public void updateEquipmentState(EquipmentState e) {
		if (e != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String sql = "UPDATE ift_equipment_status SET running_state = '" + e.getRunningState()
					+ "', communication_time = '" + sdf.format(e.getCommunicationTime()) + "', cur_time = '"
					+ sdf.format(e.getCurTime()) + "', signal_intensity = '" + e.getSignalIntensity()
					+ "', heartbean_type = '" + e.getHeartbeatType() + "', link_type = '" + e.getLinkType()
					+ "', reporting_cycle = '" + e.getReportingCycle() + "', acquisition_cycle = '"
					+ e.getAcquisionCycle() + "', storage_cycle = '" + e.getStorageCycle() + "', stored_data = "
					+ e.getStoredData() + ", unreported_data = " + e.getUnreportedData() + ", equipment_energy = "
					+ e.getEquipmentEnergy() + ", update_by = '" + e.getUpdateBy() + "', update_date = '"
					+ sdf.format(e.getUpdateDate()) + "', remarks = '" + e.getRemarks() + "', remote_address = '"
					+ e.getRemoteAddress() + "', del_flag = '" + e.getDelFlag() + "' WHERE id = '" + e.getId() + "'";
			DaoUtils.update(sql);
		} else
			;

	}

	/**
	 * 根据设备id更新设备状态
	 * 
	 * @param state
	 * @param address
	 */
	public void updateRunningState(boolean state, String address) {
		String sql = "UPDATE ift_equipment_status SET running_state = '" + (state ? "1" : "0")
				+ "',update_date = now() where remote_address = '" + address + "'";
		DaoUtils.update(sql);
	}

	/**
	 * 根据设备id型号获得编号
	 * (根据设备编号获得设备状态id)
	 * 
	 * @param address
	 * @return
	 */
	public String getByAddress(String address) {
		String sql = "SELECT id From ift_equipment_status WHERE equipment_id = ?";
		Object result = DaoUtils.getValue(sql, address);
		if (result != null)
			return result.toString();
		else
			return null;
	}
	
	public String getLinkTypeByRemote(String remote) {
		String sql = "SELECT link_type FROM ift_equipment_status WHERE remote_address = ?";
		Object result = DaoUtils.getValue(sql, remote);
		return (String) result;
	}

	/**
	 * 设备是否存在
	 * 
	 * @param address
	 * @return
	 */
	public boolean isExistEquipment(String address) {
		String sql = "SELECT count(1) From ift_equipment WHERE number = ?";
		Object result = DaoUtils.getValue(sql, address);
		System.out.println("设备是否存在" + result.toString());
		// boolean res = false;
		// if (result != null) {
		// res = true;
		// System.out.println(result);
		// }
		// System.out.println(result);
		if (result != null) {
			return Integer.parseInt(result.toString()) > 0 ? true : false;
		} else {
			return false;
		}
	}
	
	/**
	 * 根据equipment_id 判断设备是否存在于状态表
	 * @param address
	 * @return
	 */
	public boolean isExistEquipmentInStateTable(String address) {
		String sql = "SELECT count(1) From ift_equipment_status WHERE equipment_id = ?";
		Object result = DaoUtils.getValue(sql, address);
		if (result != null) {
			return Integer.parseInt(result.toString()) > 0 ? true : false;
		} else {
			return false;
		}
	}

	/**
	 * 更新控制设备状态
	 * 
	 * @param e
	 */
	public void updateState(EquipmentState e) throws Exception {
		 String sql = "UPDATE ift_equipment_status SET running_state = '" + e.getRunningState() + "',remote_address = '"
				+ e.getRemoteAddress() + "' WHERE equipment_id = '" + e.getEquipmentId() + "'";
		 DaoUtils.update(sql);
	}

    /**
     * 更新控制设备状态
     *
     * @param state
     * @param equipmentNo
     * @param channelNo
     */
    public void updateCtrlEquipmentState(final String state, final String equipmentNo, final String channelNo) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String channelId = String.valueOf(equipmentNo) + "-" + channelNo;
        final String sql = "INSERT INTO ift_ctrl_equipment_status(id, ctrl_channel_id, status, create_date, update_date)values('" + new SetIdUtils().setId() + "','" + channelId + "','" + state + "','" + sdf.format(new Date()) + "','" + sdf.format(new Date()) + "')";
        DaoUtils.update(sql);
    }

    /**
     * 通过日志id更新控制设备日志
     *
     * @param logId
     * @param remarks
     * @param state
     */
    public void updateCtrlEquipmentLogById(final String logId, final String remarks, final String state) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String sql = "UPDATE ift_ctrl_equipment_log SET return_result = '" + state + "', update_date = '" + sdf.format(new Date()) + "' WHERE remarks = '" + remarks + "' AND id = '" + logId + "'";
        DaoUtils.update(sql);
    }

    /**
     * 更新控制设备日志
     *
     * @param equipmentNo
     * @param channelNo
     * @param newState
     * @param proState
     */
    public void updateCtrlEquipmentLog(final String equipmentNo, final String channelNo, final String newState, final String proState) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String sql = "UPDATE ift_ctrl_equipment_log SET return_result = '" + newState + "', update_date = '" + sdf.format(new Date()) + "' WHERE remarks LIKE '" + equipmentNo + "-%-" + channelNo + "' AND return_result = '" + proState + "' ORDER BY request_time ASC LIMIT 1";
        DaoUtils.update(sql);
    }

	/**
	 * 更新控制设备状态
	 * @param equipmentNo
	 * @param newState
	 */
	public void updateCtrlEquipment(final String equipmentNo, final String newState) {
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final String sql = "UPDATE ift_ctrl_equipment SET is_service = '" + newState + "', update_date = '" + sdf.format(new Date()) + "' WHERE id = '" + equipmentNo + "'";
		DaoUtils.update(sql);
	}

    public void updateRelCtrlChannel(final String equipment, final String channel, final String state) {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String sql = "UPDATE col_rel_ctrl_channel SET state = '" + state + "', update_date = '" + sdf.format(new Date()) + "' WHERE ctrl_equipment_channel LIKE '" + equipment + "-%-" + channel + "'";
        DaoUtils.update(sql);
    }

	public String getRemote(String id) {
		String sql = "SELECT remote_address from ift_equipment_status WHERE equipment_id = ?";
		Object result = DaoUtils.getValue(sql, id);
		return result == null ? "" : result.toString();
	}
}
